package com.bonc.web.xss;

import com.bonc.util.string.StringUtils;

import java.util.Random;

public class SequenceTool {

    public static String getNewValue() {
        long now = System.currentTimeMillis();
        return SequenceTool.getRandomString(3) + now;
    }

    public static String getRandomString(int length) { // length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 将容易引起xss漏洞的半角字符直角接替换成全字符 在保证不删除数据的情况下保存
     * @param value
     * @return 过滤后的值
     */
    public static Object xssEncode(Object value) {
        // 判空
        if (StringUtils.isEmpty(value)) {
            return value;
        }
        if (value instanceof String) {
            String res = (String) value;
            System.out.println("替换参数危险字符开始：" + res);
            res = res.replaceAll("eval\\((.*)\\)", "");
            res = res.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
            res = res.replaceAll("(?i)<script.*?>.*?<script.*?>", "");
            res = res.replaceAll("(?i)<script.*?>.*?</script.*?>", "");
            res = res.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "");
            res = res.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", "");
            res = res.replaceAll("[|&;$%'\"\\'\\\"<>()\n\t\\\\]", "");
            System.out.println("替换参数危险字符结束：" + res);
            return res;
        }
        return value;
    }
}
